import request from "../utils/request"
import store from "../store"
import { userActionType } from "../store/modules/user"
import { getEnv, getStaticUrl } from "./settings"
import { bindPhone } from "@/pages/mine/bindPhone"
import persistence from "@/store/persistence"
import { vocabularyLearningActionType } from "@/store/modules/vocabularyLearning"

//全局登录接口
let logging = false // 是否正在登录，防止多次调用登录接口
let afterLoginRequestPromiseList = []

export function login() {
  return new Promise(async (resolve, reject) => {
    if (logging) {
      afterLoginRequestPromiseList.push({
        resolve: resolve,
        reject: reject,
      })
    } else {
      try {
        logging = true
        async function login() {
          return new Promise((resolve, reject) => {
            uni.login({
              provider: "weixin",
              success(res) {
                resolve(res)
              },
              fail(err) {
                reject(err)
              },
            })
          })
        }
        const loginRes = await login()
        //获取token和userInfo
        let shareUserId = ""
        // 推荐官活动
        // if (store.getters[userActionType.getters.recommender.id]) {
        //   shareUserId = store.getters[userActionType.getters.recommender.id]
        // } else
        // 邀请有礼活动
        if (["邀请有礼"].includes(persistence.shareType.get())) {
          shareUserId = persistence.shareUserId.get()
          persistence.shareType.set("")
          persistence.shareUserId.set("")
        }
        const res = await request({
          url: "authorize/loginByWechatApplets",
          method: "POST",
          data: {
            code: loginRes.code,
            shareUserId: shareUserId, // 邀请人id
            channelId: store.getters[userActionType.getters.channelId], //渠道id
            userFrom: store.getters[userActionType.getters.userFrom], //用户来源
            userSchool: store.getters[userActionType.getters.XWX_schoolName], //校务行用户来源学校
          },
          showLoading: true,
          noAuth: true, //标记该接口不需要鉴权
        })
        logging = false
        resolve(res)
        // 执行登陆后的钩子
        for (let item of afterLoginRequestPromiseList) {
          item.resolve(res)
        }
        afterLoginRequestPromiseList = []
        //登陆完执行一个请求
        if (res && res.token) {
          await request({
            url: "statistics/checkInAndUserStats",
            noAuth: true,
            header: {
              "k-Authorization": res.token,
            },
          }).catch((e) => {
            console.log(e, "err")
          })
        }
      } catch (e) {
        console.log(e, "error")
        await showModal({
          title: "提示",
          content: e,
          showCancel: false,
        })
        logging = false
        reject(e)
        // 执行登陆后的钩子
        for (let item of afterLoginRequestPromiseList) {
          item.reject(e)
        }
        afterLoginRequestPromiseList = []
      }
    }
  })
}

//判断是否为空，其中数字0不为空
export function valIsEmpty(val) {
  return val == null || val === "" || val === undefined || val === "<p><br></p>"
}

//将params中的参数拼接到url中
export function handleUrlParams(url, params) {
  //判断params是否为空
  if (valIsEmpty(params)) {
    return url
  }
  //判断url中是否有参数
  if (url.indexOf("?") === -1) {
    url += "?"
  }
  //判断url中是否已经有参数
  if (url.indexOf("=") !== -1) {
    url += "&"
  }
  //遍历params
  for (let key in params) {
    url += key + "=" + params[key] + "&"
  }
  //去掉最后一个&
  url = url.substring(0, url.length - 1)
  return url
}

/**
 * @see 获取用于展示的图片
 * 无http和base64开头,则添加全局静态资源地址
 */
export function getShowImage(url) {
  if (!url) return url
  let reg = /http(s)?/
  let base64Reg = /^data:image/
  if (reg.test(url) || base64Reg.test(url)) {
    return url
  } else {
    return getStaticUrl() + url
  }
}

export const showToast = {
  error(msg, duration = 1500) {
    uni.showToast({
      title: msg,
      icon: "error",
      mask: true,
      duration: duration,
    })
  },
  success(msg, duration = 1500) {
    uni.showToast({
      title: msg,
      icon: "success",
      mask: true,
      duration: duration,
    })
  },
  default(msg, duration = 1500) {
    uni.showToast({
      title: msg,
      mask: true,
      duration: duration,
      icon: "none",
    })
  },
}

//将原有的uniapp的showModal改为promise形式，方便同步处理；title: 标题，content: 内容，showCancel: 是否显示取消按钮，confirmText: 确认按钮文字，cancelText: 取消按钮文字
export function showModal(obj) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...obj,
      success(res) {
        if (res.confirm) {
          resolve(true)
        } else {
          resolve(false)
        }
      },
      fail(err) {
        console.log(err, "err")
        reject(err)
      },
    })
  })
}
//将原有的uniapp的showModal改为promise形式，方便同步处理；title: 标题，content: 内容，showCancel: 是否显示取消按钮，confirmText: 确认按钮文字，cancelText: 取消按钮文字
export function showModalPromise(obj) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...obj,
      success(res) {
        if (res.confirm) {
          resolve(true)
        } else {
          reject(false)
        }
      },
    })
  })
}

//深拷贝
export function cloneDeep(obj) {
  return JSON.parse(JSON.stringify(obj))
}

//用于将单位为分的金额处理成元，并保留两位小数，同时把末尾多余的0去掉
export function handleMoney(money) {
  if (!money) {
    return 0
  }
  money = money / 100
  money = money.toFixed(2)
  money = money.replace(/0+$/, "")
  money = money.replace(/\.$/, "")
  return money
}

//将单位为分的金额处理成元
export function handleMonkeyRow(money) {
  if (!money) {
    return 0
  }
  money = money / 100
  money = money.toFixed(2)
  return money
}

//检查用户是否有绑定手机号码，如果没有则跳转到绑定手机号码页面，没有绑定手机号码返回 false；绑定了手机号码返回 true
export async function checkBindPhone(redirectUrl, message) {
  //开发环境不校验手机号码
  // if (getEnv() === "develop") {
  //   return true
  // }
  const userInfo = await store.dispatch(userActionType.action.userInfo)
  const params = {}
  if (!userInfo.phone) {
    if (redirectUrl) {
      params.redirectUrl = encodeURIComponent(redirectUrl)
    }
    if (message) {
      params.message = message
    }
    uni.navigateTo({
      url: handleUrlParams("/pages/mine/bindMobilePhone", params),
    })
    return false
  } else {
    return true
  }
}

//复制文字
export function copyText(text) {
  uni.setClipboardData({
    data: text,
    success() {
      showToast.success("复制成功")
    },
  })
}

/**
 * @see 解析树形菜单
 */
export function list2tree(
  data,
  parentId = "0",
  parentKey = "menuParentId",
  menuKey = "menuId",
  hierarchyLevel = 0, //嵌套等级
) {
  let tree = []
  hierarchyLevel++
  data.forEach((v) => {
    if (String(v[parentKey]) === String(parentId)) {
      v.hierarchyLevel = hierarchyLevel
      tree.push(v)
      v.children = list2tree(data, v[menuKey], parentKey, menuKey, hierarchyLevel)
    }
  })
  return tree
}
// 树形菜单按某个字段排序
function sortTree(tree, sortKey = "sort", childrenKey = "children") {
  tree.sort((a, b) => a[sortKey] - b[sortKey])
  tree.forEach((item) => {
    if (item[childrenKey]) {
      sortTree(item[childrenKey])
    }
  })
  return tree
}

//判断用户是否是会员
export async function isVip() {
  //如果在系统参数里开启了免vip
  let res = await request({
    url: "sysPam/getSysParam",
    data: {
      pamCode: "closeVip",
    },
    errorHandle: true,
    showLoading: true,
  })
  if (res.pamValue === "是") return true
  const userInfo = await store.dispatch(userActionType.action.userInfo)
  if (userInfo.memberInfo) {
    return true
  } else {
    return false
  }
}

//生成一串包含英文字母和数字的随机字符串，传入参数用于控制字符串的长度
export function randomString(len) {
  len = len || 32
  let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
  let maxPos = $chars.length
  let pwd = ""
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

//构造一个节流函数
export function throttle(fn, delay, that) {
  let timer = null
  return function () {
    if (timer) {
      return
    }
    timer = setTimeout(() => {
      fn.apply(that)
      timer = null
    }, delay)
  }
}

//根据系统参数的key获取系统参数的值
export async function getSysParam(pamCode) {
  let res = await request({
    url: "sysPam/getSysParam",
    data: {
      pamCode: pamCode,
    },
    errorHandle: true,
    showLoading: true,
  })
  return res ? res.pamValue : ""
}

//将两个对象之间的属性进行赋值，将obj2的属性赋值给obj1
export function assignObj(obj1, obj2) {
  for (let key in obj1) {
    if (obj2[key] !== undefined) {
      obj1[key] = obj2[key]
    }
  }
  return obj1
}

//将一个对象的所有属性置空，字符串置为空字符串，数字置为0，数组置为空数组，对象置为空对象，布尔值置为false
export function clearObj(obj) {
  for (let key in obj) {
    if (valIsEmpty(obj[key])) {
      continue
    } else if (typeof obj[key] === "string") {
      obj[key] = ""
    } else if (typeof obj[key] === "number") {
      obj[key] = 0
    } else if (Array.isArray(obj[key])) {
      obj[key] = []
    } else if (typeof obj[key] === "boolean") {
      obj[key] = false
    } else if (typeof obj[key] === "object") {
      obj[key] = {}
    }
  }
  return obj
}

// 是否要进入精简版小程序（屏蔽任何付费板块）
export async function isSimpleApp() {
  const userInfo = await store.dispatch(userActionType.action.userInfo)
  return ["XWX_USER"].includes(userInfo.userFrom)
}


// 为富文本指定的标签添加attr属性
export function richTextAddAttrForTag(html, tag, attr) {
  const reg = new RegExp(`<${tag}`, "g")
  return html.replace(reg, `<${tag} ${attr}`)
}
